<?php
/**
 * Auther: Joshua Conero
 * Date: 2017/5/15 0015 22:16
 * Email: brximl@163.com
 * Name: 系统管理
 */

namespace app\common\traits;
use app\common\model\Role;
use hyang\Dataset;
use think\Db;
use think\facade\Request;

trait Admin
{
    protected $current_menuid = 'v0.5.admin_tpl';
    /**
     * 页面模板
     * @param $callback
     * @return mixed
     */
    protected function pageTpl($callback){
        $this->authCheckOut();
        // 数据集
        $dataset = new Dataset();
        call_user_func($callback,$dataset);
        // 页面渲染
        $this->assign('pageContent', view(
            ROOT_PATH.'app/admin/view/'. strtolower(Request::controller()).'/'.Request::action().'.html',
            $dataset->getSets())->getContent()
        );

        $menu = $this->getSysMenu($this->current_menuid,true);
        $admin = [];
        $xhtml = '';
        $requset = \request();
        $curUrl = strtolower('/'.$requset->module().'/'.$requset->controller());
        $role = new Role();
        $roles = $role->getRoles();
        foreach ($menu as $k=>$v){
            $access_role = $v['access_role'];
            // 通过交集处理
            if(!empty($access_role)){
                $access_role = explode(',', $access_role);
                $hasRight = array_intersect($access_role, $roles);
                if(empty($hasRight)){
                    continue;
                }
            }
            $value = $v['text'];
            $icon = $v['icon'];
            $icon = $icon? (substr_count($icon,'/') > 0? '<img src="'.$icon.'">':'<i class="'.$icon.'"></i>'):'';
            if($icon) $icon .= ' ';
            $xhtml .= '<a href="'.$k.'" class="list-group-item '.
                (substr_count($k,$curUrl) > 0? 'active':'list-group-item-action').'">'.$icon.$value.'</a>';
        }
        if($xhtml) $admin['menu'] = $xhtml;
        $this->assign('admin',$admin);
        return $this->fetch(ROOT_PATH. 'app/admin/view/admin.html');
    }

    /**
     * 权限控制
     */
    protected function authCheckOut(){
        $hasVisitAuth = $this->hasVisitAuth();
        if($hasVisitAuth){
            return $hasVisitAuth;
        }
        // ajax 请求
        if($this->request->isAjax()){
            $this->response(['code'=>-1, 'msg'=>'您不具备相应的操作权限'], 'json', 200);
            die();
        }
        $this->getErrorUrl('地址请求无效');
    }

    /**
     * 请求权限检测
     * @return bool
     */
    protected function hasVisitAuth(){
        $role = new Role();
        $roles = $role->getRoles();
        $ctl = strtolower($this->request->controller());
        $menu = Db::table('sys_menu')
            ->where(['group_mk'=>$this->current_menuid, 'controller'=>$ctl])
            ->find()
            ;
        // 单模块测试检测
        if($menu && !empty($menu['access_role'])){
            $access_role = explode(',', $menu['access_role']);
            $hasRight = array_intersect($access_role, $roles);
            if(empty($hasRight)){
                return false;
            }
        }
        if($roles && is_array($roles) && (in_array('developer', $roles) || in_array('admin', $roles))){
            return true;
        }
        return false;
    }

    /**
     * 模块私有方法
     * @param $callback
     * @return \think\response\Json
     */
    protected function uModuleApiTpl($callback){
        $hasVAuth = $this->hasVisitAuth();
        $data = [];
        if(!$hasVAuth){
            $data = ['code'=>-1, 'msg'=>'您没有接口的访问权限'];
        }
        else{
            $data = call_user_func($callback);
            if(is_array($data)){
                $data['code'] = 1;
                $data['msg'] = '';
            }elseif (is_string($data)){
                $data = ['code'=>-1, 'msg'=>$data];
            }
        }
        return json($data);
    }
    /**
     * 获取系统菜单相关参数
     */
    protected function getParamFromMenu($name){
        $row = Db::table('sys_menu')
            ->field('icon,descrip')
            ->where(['group_mk'=>$this->current_menuid,'controller'=>$name])
            ->find();
        return $row;
    }
}